<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>管理员后台</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.3.0/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body {
            background-color: #f8f9fa;
            padding: 20px;
        }

        .admin-container {
            max-width: 1200px;
            margin: 0 auto;
            background-color: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }

        .form-group {
            margin-bottom: 15px;
        }

        #desc,
        #head,
        #test_input,
        #test_output {
            font-family: monospace;
            min-height: 100px;
        }

        .question-list {
            margin-top: 30px;
        }

        .question-list table {
            width: 100%;
        }

        .question-actions {
            white-space: nowrap;
        }

        .nav-tabs {
            margin-bottom: 20px;
        }
    </style>
</head>

<body>
    <div class="admin-container">
        <ul class="nav nav-tabs" id="adminTabs" role="tablist">
            <li class="nav-item" role="presentation">
                <button class="nav-link active" id="questions-tab" data-bs-toggle="tab" data-bs-target="#questions" type="button" role="tab">题目列表</button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" id="add-tab" data-bs-toggle="tab" data-bs-target="#add" type="button" role="tab">添加题目</button>
            </li>
        </ul>

        <div class="tab-content">
            <div class="tab-pane fade show active" id="questions" role="tabpanel">
                <h3>题目列表</h3>
                <div class="table-responsive">
                    <table class="table table-striped">
                        <thead>
                            <tr>
                                <th>编号</th>
                                <th>标题</th>
                                <th>难度</th>
                                <th>CPU限制</th>
                                <th>内存限制</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="questionList">
                            <!-- 题目列表将通过JavaScript动态加载 -->
                        </tbody>
                    </table>
                </div>
            </div>

            <div class="tab-pane fade" id="add" role="tabpanel">
                <h3>添加/编辑题目</h3>
                <form id="questionForm">
                    <input type="hidden" id="isEdit" value="false">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="number">题目编号</label>
                                <input type="text" class="form-control" id="number" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="title">题目标题</label>
                                <input type="text" class="form-control" id="title" required>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-4">
                            <div class="form-group">
                                <label for="star">难度</label>
                                <select class="form-control" id="star" required>
                                    <option value="简单">简单</option>
                                    <option value="中等">中等</option>
                                    <option value="困难">困难</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group">
                                <label for="cpu_limit">CPU限制(ms)</label>
                                <input type="number" class="form-control" id="cpu_limit" required>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group">
                                <label for="mem_limit">内存限制(MB)</label>
                                <input type="number" class="form-control" id="mem_limit" required>
                            </div>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="desc">题目描述</label>
                        <textarea class="form-control" id="desc" rows="5" required></textarea>
                    </div>

                    <div class="form-group">
                        <label for="test_input">测试用例输入</label>
                        <textarea class="form-control" id="test_input" rows="3" required></textarea>
                    </div>

                    <div class="form-group">
                        <label for="test_output">测试用例输出</label>
                        <textarea class="form-control" id="test_output" rows="3" required></textarea>
                    </div>

                    <div class="d-grid gap-2">
                        <button type="submit" class="btn btn-primary" id="submitBtn">添加题目</button>
                        <button type="button" class="btn btn-secondary" id="cancelBtn" style="display: none;">取消编辑</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.3.0/js/bootstrap.bundle.min.js"></script>
    <script>
        // 加载题目列表
        function loadQuestions() {
            console.log('开始加载题目列表...');
            $.get('/all_questions', function(data) {
                console.log('获取到的原始数据:', data);
                const questions = $(data).find('tr');
                console.log('找到的题目行数:', questions.length);
                let questionList = '';
                questions.each(function() {
                    const number = $(this).find('td:eq(0)').text();
                    const title = $(this).find('td:eq(1)').text();
                    const star = $(this).find('td:eq(2)').text();
                    const cpuLimit = $(this).find('td:eq(3)').text() || '1';
                    const memLimit = $(this).find('td:eq(4)').text() || '50000';
                    console.log('处理题目:', {number, title, star, cpuLimit, memLimit});
                    if (number && title && star) {
                        questionList += `
                            <tr>
                                <td>${number}</td>
                                <td>${title}</td>
                                <td>${star}</td>
                                <td>${cpuLimit}</td>
                                <td>${memLimit}</td>
                                <td class="question-actions">
                                    <button class="btn btn-sm btn-primary edit-btn" data-number="${number}">编辑</button>
                                    <button class="btn btn-sm btn-danger delete-btn" data-number="${number}">删除</button>
                                </td>
                            </tr>
                        `;
                    }
                });
                console.log('生成的题目列表HTML:', questionList);
                $('#questionList').html(questionList);
            }).fail(function(xhr, status, error) {
                console.error('加载题目列表失败:', {xhr, status, error});
            });
        }

        // 加载题目详情
        function loadQuestionDetail(number) {
            console.log('开始加载题目详情, 题目编号:', number);
            $.get(`/question/${number}`, function(data) {
                console.log('获取到的题目详情原始数据:', data);
                const question = $(data);
                
                // 设置基本字段
                $('#number').val(number);
                
                // 获取题目标题
                const title = question.find('.question-title').text().trim()
                    .replace(/^\d+\.\s*/, '')  // 移除开头的题号
                    .replace(/\s+(简单|中等|困难)\s*$/, '');  // 移除末尾的难度值
                console.log('提取的题目标题:', title);
                $('#title').val(title);
                
                // 获取难度
                const star = question.find('.question-star').text().trim();
                console.log('提取的难度值:', star);
                $('#star').val(star);
                
                // 获取题目描述
                const desc = question.find('.question-desc').html() || '';
                const cleanDesc = $('<div>').html(desc).text().trim();
                console.log('提取的题目描述:', cleanDesc);
                $('#desc').val(cleanDesc);
                
                // 获取测试用例
                const testInput = question.find('[name="test_input"]').text().trim();
                const testOutput = question.find('[name="test_output"]').text().trim();
                console.log('提取的测试用例:', {testInput, testOutput});
                $('#test_input').val(testInput);
                $('#test_output').val(testOutput);
                
                // 获取CPU和内存限制
                const cpuLimit = question.find('[name="cpu_limit"]').text().trim();
                const memLimit = question.find('[name="mem_limit"]').text().trim();
                console.log('提取的资源限制:', {cpuLimit, memLimit});
                $('#cpu_limit').val(cpuLimit || 1);
                $('#mem_limit').val(memLimit || 50000);
                
                // 更新表单状态
                $('#isEdit').val('true');
                $('#submitBtn').text('更新题目');
                $('#cancelBtn').show();
                
                // 切换到编辑表单标签页
                $('#adminTabs button[data-bs-target="#add"]').tab('show');
                
                console.log('题目详情加载完成，表单字段值:', {
                    number: $('#number').val(),
                    title: $('#title').val(),
                    star: $('#star').val(),
                    desc: $('#desc').val(),
                    test_input: $('#test_input').val(),
                    test_output: $('#test_output').val(),
                    cpu_limit: $('#cpu_limit').val(),
                    mem_limit: $('#mem_limit').val()
                });
            }).fail(function(xhr, status, error) {
                console.error('加载题目详情失败:', {xhr, status, error});
                alert('加载题目详情失败，请重试');
            });
        }

        // 删除题目
        $(document).on('click', '.delete-btn', function() {
            if (confirm('确定要删除这道题目吗？')) {
                const number = $(this).data('number');
                console.log('准备删除题目:', number);  // 添加调试日志
                $.ajax({
                    url: `/admin/delete_question/${number}`,
                    type: 'DELETE',
                    success: function(response) {
                        console.log('删除请求响应:', response);  // 添加调试日志
                        if (response.status === 0) {
                            alert('删除题目成功');
                            loadQuestions();
                        } else {
                            alert(response.message || '删除题目失败');
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error('删除请求失败:', {xhr, status, error});  // 添加错误日志
                        alert('删除题目失败，请重试');
                    }
                });
            }
        });

        // 编辑题目
        $(document).on('click', '.edit-btn', function() {
            const number = $(this).data('number');
            loadQuestionDetail(number);
        });

        // 取消编辑
        $('#cancelBtn').click(function() {
            $('#questionForm')[0].reset();
            $('#isEdit').val('false');
            $('#submitBtn').text('添加题目');
            $('#cancelBtn').hide();
        });

        // 提交表单
        $('#questionForm').on('submit', function(e) {
            e.preventDefault();
            const isEdit = $('#isEdit').val() === 'true';
            const url = isEdit ? '/admin/update_question' : '/admin/add_question';
            const method = isEdit ? 'PUT' : 'POST';

            $.ajax({
                url: url,
                type: method,
                contentType: 'application/json',
                data: JSON.stringify({
                    number: $('#number').val(),
                    title: $('#title').val(),
                    star: $('#star').val(),
                    desc: $('#desc').val(),
                    head: '',  // 设置为空字符串
                    test_input: $('#test_input').val(),
                    test_output: $('#test_output').val(),
                    cpu_limit: parseInt($('#cpu_limit').val()),
                    mem_limit: parseInt($('#mem_limit').val())
                }),
                success: function(response) {
                    if (response.status === 0) {
                        alert(isEdit ? '更新题目成功' : '添加题目成功');
                        $('#questionForm')[0].reset();
                        $('#isEdit').val('false');
                        $('#submitBtn').text('添加题目');
                        $('#cancelBtn').hide();
                        loadQuestions();
                        $('#adminTabs button[data-bs-target="#questions"]').tab('show');
                    } else {
                        alert(response.message);
                    }
                },
                error: function() {
                    alert(isEdit ? '更新题目失败，请重试' : '添加题目失败，请重试');
                }
            });
        });

        // 初始化加载题目列表
        $(document).ready(function() {
            loadQuestions();
        });
    </script>
</body>

</html>